<template>
    <div class="box-container">
        <!-- 搜索 -->
         <div class="top-main">
            <el-form  class="top-form-fl" :model="param" label-width="auto" :inline="true">
            <el-form-item label="登录账号:">
                <el-input v-model="param.name" placeholder="请输入登录账号" clearable/>
            </el-form-item>
            <el-form-item label="员工姓名:">
                <el-input v-model="param.nickname" placeholder="请输入员工姓名" clearable/>
            </el-form-item>
            <el-form-item label="审核日期:" style="width: 400px;">
                <el-col :span="11">
                    <el-date-picker v-model="param.beginExamineTime" type="date" placeholder="选择开始日期"
                        style="width: 100%" />
                </el-col>
                <el-col :span="2" class="text-center">
                    <span class="text-gray-500">-</span>
                </el-col>
                <el-col :span="11">
                    <el-date-picker v-model="param.endExamineTime" type="date" placeholder="选择结束日期"
                        style="width: 100%" />
                </el-col>
            </el-form-item>
            <el-form-item label="注册日期:" style="width: 400px;">
                <el-col :span="11">
                    <el-date-picker v-model="param.beginCreateTime" type="date" placeholder="选择开始日期"
                        style="width: 100%" />
                </el-col>
                <el-col :span="2" class="text-center">
                    <span class="text-gray-500">-</span>
                </el-col>
                <el-col :span="11">
                    <el-date-picker v-model="param.endCreateTime" type="date" placeholder="选择结束日期"
                        style="width: 100%" />
                </el-col>
            </el-form-item>
            <el-form-item label="手机号:">
                <el-input v-model="param.mobile" placeholder="请输入手机号" clearable/>
            </el-form-item>
        </el-form>
        <div class="top-from-fr">
            <el-button class="top-Search" @click="getUserListdata" type="primary">搜索</el-button>
            <el-button class="top-Refresh" @click="resetFrome">重置</el-button>
        </div>   
        </div>
        <!-- 修改用户权限弹窗 -->
        <el-dialog v-model="param.dialogUserRole" title="编辑权限" @close="cancel" width="400px">
            <el-form :model="permissions">
                <!-- <el-form-item label="企业角色">
                    <el-select v-model="permissions.roleIds" multiple filterable allow-create default-first-option
                        :reserve-keyword="false" placeholder="请选择企业角色">
                        <el-option label="贷代" value="5" />
                        <el-option label="集装箱公司" value="10" />
                        <el-option label="卖箱" value="15" />
                        <el-option label="集卡车队" value="20" />
                        <el-option label="堆场" value="25" />
                    </el-select>
                </el-form-item> -->
                <el-form-item label="角色权限">
                    <el-select v-model="permissions.roleIds" multiple filterable allow-create default-first-option
                        :reserve-keyword="false" placeholder="请选择角色权限">
                        <el-option v-for="item in permissions.rolePermissionList" :key="item.id" :label="item.name"
                            :value="item.id" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="cancel">取消</el-button>
                    <el-button type="primary" @click="updateUserRole">确定</el-button>
                </div>
            </template>
        </el-dialog>
        <Table v-bind="tableData" style="width: 100%;" @deleteBox="deleteBox" @handleSwitch="handleSwitch"
            @reject="setReject" @pageChange="pageChange" @pass="setPass" @editPermissions="editPermissions">
        </Table>
    </div>
</template>
<script setup long="ts">
import { reactive, onMounted } from 'vue';
// import { getTable } from '@/api/enterpriseManage/index'
import Table from '@/views/components/table/index.vue';
import { updateSysUserRole, getUserListPlatforms, getCompanyPage, updateSysUserExamineStatus, delUser, userStatus, getRolePermission,getRoleDetailById } from '@/api/enterpriseManage/index'
import { updateSysCompanyExamineStatus } from '@/api/enterpriseManage/index'

import { Plus, Delete, Edit, Message, Download, Upload } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
const param = reactive({
    loading: false,
    name: '',
    nickname: '',
    beginExamineTime: '',
    endExamineTime: '',
    beginCreateTime: '',
    endCreateTime: '',
    mobile: '',
    phoneNum: '',
    pageNum: 1,
    pageSize: 10,
    dialogUserRole: false
})
const tableData = reactive({
    header: [
        { key: 'username', colWidth: '60', colheight: '80', title: '登陆账号', type: 'username', isCheck: true },
        { key: 'nickname', colWidth: '60', colheight: '80', title: '员工姓名', type: 'nickname', isCheck: true },
        { key: 'roleNames', colWidth: '60', colheight: '80', title: '角色', type: 'roleNames', isCheck: true },
        { key: 'userType', colWidth: '60', colheight: '80', title: '账号类型', type: 'userType', isCheck: true },
        { key: 'companyName', colWidth: '100', colheight: '80', title: '所属企业', type: 'companyName', isCheck: true },
        { key: 'mobile', colWidth: '80', title: '手机号', type: 'mobile', isCheck: true },
        { key: 'createTime', colWidth: '50', title: '注册日期', type: 'createTime', isCheck: true },
        { key: 'examineTime', colWidth: '60', title: '审核日期', type: 'examineTime', isCheck: true },
        { key: 'periodValidity', colWidth: '120', title: '认证有效期', type: 'periodValidity', isCheck: true },
        { key: 'examineStatus', colWidth: '60', title: '认证状态', type: 'examineStatus', isCheck: true },
        { key: 'status', colWidth: '60', title: '状态', type: 'status', isCheck: true },
        {
            key: 'operateBut',
            colWidth: '80',
            title: '操作',
            type: 'operateBut',
            isCheck: true,
            buttons: [
                {
                    icon: 'Open',
                    type: 0,  //企业用户 1  企业账号 0 
                    status: "1",
                    command: 'handleSwitch',
                    content: '是否启用',
                    isShow:true,

                },
                {
                    icon: 'EditPen',
                    type: 0,  //企业用户 1  企业账号 0 
                    command: 'pass',
                    content: '审核',
                    isShow:false,

                },
                // {
                //     icon: 'Delete',
                //     type: 0,  //企业用户 1  企业账号 0 
                //     command: 'deleteBox',
                //     content: '删除',
                //     isShow:true,

                // },
                // {
                //     icon: 'TurnOff',
                //     type: 0,  //企业用户 1  企业账号 0 
                //     status: "1",
                //     command: 'reject',
                //     content: '驳回',
                //     isShow:true,
                // },
                {
                    icon: 'Edit',
                    type: 0,  //企业用户 1  企业账号 0 
                    status: "1",
                    command: 'editPermissions',
                    content: '编辑',
                    isShow:true,

                }
            ]
        }
    ],
    data: [],
    config: {
        isSelection: false,
        isList: false,
        isPagination: true, // 是否分页
        total: 0, // 总条数
        loading: false,
        isRealName: false, // 是否已经实名认证
    }
})
const permissions = reactive({
    id: '',
    roleIds: '',
    roleNames: '',
    rolePermissionList: []

})
//清空所有填写搜索信息
const resetFrome = () => {
    param.name = null
    param.nickname = null
    param.beginExamineTime = null
    param.endExamineTime = null
    param.beginCreateTime = null
    param.endCreateTime = null
    param.mobile = null

}
onMounted(() => {
    getUserListdata()
    // getPermission()
})

const setReject = (val) => {
    ElMessageBox.prompt('请输入驳回原因', '您确定要驳回该条申请吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '关闭',
        inputPattern: /\S/,
        inputErrorMessage: '驳回原因',
    }).then(({ value }) => {
        const data = { id: val, examineStatus: 15, rejectReason: value }
        updateSysCompanyExamineStatus(JSON.stringify(data)).then(res => {
            getUserListdata()
            ElMessage({
                type: 'success',
                message: '驳回申请成功',
            })
        }).cache(() => {
            ElMessage({
                type: 'info',
                message: '驳回申请失败',
            })
        })
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '驳回申请失败',
        })
    })
}
const setPass = (val) => {
    const data = { id: val, examineStatus: 10, rejectReason: '' }
    updateSysUserExamineStatus(JSON.stringify(data)).then(res => {
        getUserListdata()
        ElMessage({
            type: 'success',
            message: '通过操作成功',
        })
    })
}

// 删除用户
const deleteBox = (row) => {
    if (row.examineStatus == "10") {
        ElMessage.warning('该用户已通过审核，不能删除')
    } else {
        ElMessageBox.confirm(
            '您确认删除该用户信息，请谨慎操作',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        ).then(() => {
            delUser(row).then((res) => {
                if (res.code == '00000') {
                    getUserListdata()
                    ElMessage.success('删除成功')
                } else {
                    ElMessage.warning(res.msg)
                }
            })
        })
            .catch(() => {
                ElMessage.info('取消删除')
            })
    }
}

//修改账号状态
const handleSwitch = (rowId, statu) => {
  let messTitle = ''
  if (statu == '1') {
    messTitle = '您确定开启该用户登录，请谨慎操作！'
  } else if (statu == '0') {
    messTitle = '您确定停止该用户登录，请谨慎操作！'
  }
  ElMessageBox.confirm(
    messTitle,
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
        userStatus(rowId, statu).then(res => {
        console.log(res)
        getUserListdata()
        ElMessage.success('状态修改成功')
      }).catch(error => {
        ElMessage.warning('状态修改失败')
      })
    })

}
const editPermissions = (val) => {
    permissions.id = val
    param.dialogUserRole = true
    getRoleDetail(val)

}
const getPermission = (id,ids) => {
    let data={
        companyId:id
    }
    getRolePermission(data).then(res => {
        if (res.data) {
            permissions.rolePermissionList = res.data
             let roleId=ids.split(",") || []
            let roleIdList=[]
            roleId.forEach((item)=>{
                roleIdList.push(parseInt(item))
            })
            permissions.roleIds=roleIdList
        }
    })
}
//详情查询
const getRoleDetail=(row)=>{
  getRoleDetailById(row).then(res => {
    getPermission(res.data.companyId,res.data.roleIds)
    // form.value=res.data
    // let roleId=res.data.roleId.split(",") || []
    // let roleIdList=[]
    // roleId.forEach((item)=>{
    //   roleIdList.push(parseInt(item))
    // })
    // form.value.roleId=roleIdList
  })
}
// 修改角色权限
const updateUserRole = () => {
    console.log(permissions.id, "--", permissions.roleIds)
    if (permissions.id && permissions.roleIds.length==0) return ElMessage.warning('企业角色/角色权限不能为空！')
    const data = {
        "id": permissions.id,
        "roleId": permissions.roleIds.join(',')
    }
    // console.log(data)
    updateSysUserRole(JSON.stringify(data)).then(res => {
        console.log(res)
        if (res.code == '00000') {
            cancel()
            getUserListdata()
        }
    })
}
//关闭弹框
const cancel = () => {
    permissions.id=''
    permissions.roleNames=''
    permissions.roleIds=''
    param.dialogUserRole=false
}
//获取收索数据
const getFilterData = () => {
    param.pageNum=1
    getUserListdata()
}
const getUserListdata = () => {
    const data = {
         username: param.name,
        nickname: param.nickname,
        beginExamineTime: param.beginExamineTime,
        endExamineTime: param.endExamineTime,
        beginCreateTime: param.beginCreateTime,
        endCreateTime: param.endCreateTime,
        mobile: param.mobile,
        pageNum: param.pageNum,
        pageSize: param.pageSize
    }
    getUserListPlatforms(data).then(res => {
        console.log(res)
        tableData.data = res.data.list
        tableData.config.total = res.data.total
    })
}
// 翻页控制
const pageChange = (val) => {
 param.pageNum = val.pageNum;
  param.pageSize = val.pageSize;
  getUserListdata()
}
</script>
<style scoped lang="scss">
    .box-container{
    padding: 20px;
}
</style>